package com.project.ryudo.SessionBean;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.FlushModeType;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.project.entity.Account;
import com.project.entity.Property;
import com.project.entity.VisitLog;

/**
 * Session Bean implementation class VisitLogBean
 */
@Stateless
@LocalBean
public class VisitLogBean implements VisitLogBeanRemote {

    /**
     * Default constructor. 
     */
	@PersistenceContext
 	EntityManager em;
    public VisitLogBean() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public void addLog(Account acc,Property prop) {
		Account tempAcc = em.find(Account.class,acc.getAccID());
		Property tempProp = em.find(Property.class,prop.getPropID());
		
		if(checkRecordExists(tempAcc,tempProp))
		{
			VisitLog vl = new VisitLog();
			vl.setAccount(acc);
			vl.setProperty(prop);
			em.persist(vl);
		}
		
		
	}

	@Override
	public boolean checkRecordExists(Account acc, Property prop) {
		Query query = em.createQuery("select vlog from VisitLog vlog where vlog.account.accID = :accID and vlog.property.propID = :propID");
		
		query.setParameter("accID", acc.getAccID());
		query.setParameter("propID", prop.getPropID());
		
		List result = query.getResultList();
		if(result.size() != 0)
		{
			VisitLog found = (VisitLog)result.get(0);
			VisitLog originalLog = em.find(VisitLog.class,found.getLogID());
			originalLog.setCount(originalLog.getCount() + 1);
			return false;
		} else {
			return true;
		}
		
	}
	
	

}
